package pt.eden.apps.tomcatjms.web;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;

/**
 *
 */
public class ResourcesServlet extends HttpServlet {

    private static final String JNDI_PREFIX = "java:comp/env/";
    
    private static final String MESSAGE_TEMPLATE = "<p>{0}</p>";

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        Context ctx = null;
        
        String message = "";
        try {
            ctx = new InitialContext();
        } catch (NamingException e) {
            message = "could not create context. " + e;
        }

        if (ctx != null) {
            try {
                ConnectionFactory connection = (ConnectionFactory) ctx.lookup(JNDI_PREFIX + "jms/ConnectionFactory");
                Topic topic = (Topic) ctx.lookup(JNDI_PREFIX + "jms/Topic");

                message = "Connection successfully created!";
            } catch (NamingException e) {
                message = "could not create resource. " + e;
            }
        }

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        out.println(MessageFormat.format(MESSAGE_TEMPLATE, message));
        out.flush();
        out.close();
    }
}
